import { useI18n } from '@/hooks/web/useI18n'
import { CrudSchema } from '@/hooks/web/useCrudSchemas'
import { useValidator } from '@/hooks/web/useValidator'
import { ElDivider, ElSwitch, ElSelect, ElOption, ElMessage } from 'element-plus'
import { useEnumeratePicker, calculateColumnWidth } from '@/utils'
import { setAllowZeroStockSaleApi } from '@/api/inventory'

const { t } = useI18n()

const { required } = useValidator()
export default function (schemaParams: any = {}) {
  const crudSchemas = reactive<CrudSchema[]>([
    {
      field: 'selection',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        type: 'selection',
        headerAlign: 'center',
        align: 'center',
        width: 30
      }
    },
    {
      field: 'id',
      label: t('inventory.id'),
      align: 'center',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        width: 60
      }
    },
    {
      field: 'name',
      label: t('inventory.cname'),
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        minWidth: 230,
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return <span style="white-space: pre-wrap">{data.row.product_name}</span>
          }
        }
      }
    },
    {
      field: 'purchase_no',
      label: t('purchase.purchase_no'),
      search: {
        component: 'Input'
      },
      form: {
        hidden: true
      },
      table: {
        hidden: true
      },
      detail: {
        hidden: true
      }
    },
    {
      field: 'hashrate',
      label: t('inventory.hashRate'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.hashRate
          }
        }
      }
    },
    {
      field: 'sku',
      label: t('inventory.sku'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'warehouse_name',
      label: t('inventory.warehouse'),
      search: {
        component: 'TreeSelect',
        componentProps: {
          checkStrictly: true,
          filterable: true,
          data: schemaParams.warehouseList ? schemaParams.warehouseList : []
        }
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        minWidth: 120,
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.warehouse_value
          }
        }
      }
    },
    {
      field: 'is_futures',
      label: t('inventory.is_futures'),
      search: {
        component: 'Select',
        componentProps: {
          options: schemaParams.is_futuresList ? schemaParams.is_futuresList : []
        }
      },
      form: {
        hidden: true,
        component: 'Input'
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.is_futures_value
          }
        }
      },
      detail: {
        hidden: true
      }
    },
    {
      field: 'source_table',
      label: t('inventory.source_table'),
      search: {
        component: 'Select',
        componentProps: {
          options: schemaParams.source_tableList ? schemaParams.source_tableList : []
        }
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return useEnumeratePicker(schemaParams.source_tableList.value, data.row.source_table)
          }
        }
      }
    },
    {
      field: 'arrival_date',
      label: t('inventory.arrival_date'),
      search: {
        component: 'DatePicker',
        componentProps: {
          valueFormat: 'YYYY-MM-DD',
          type: 'daterange',
          unlinkPanels: true,
          rangeSeparator: '-'
        }
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        minWidth: 100,
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.arrival_date
          }
        }
      }
    },
    {
      field: 'real_arrival_date',
      label: t('inventory.real_arrival_date'),
      search: {
        component: 'DatePicker',
        componentProps: {
          valueFormat: 'YYYY-MM-DD',
          type: 'daterange',
          unlinkPanels: true,
          rangeSeparator: '-'
        }
      },
      form: {
        component: 'DatePicker',
        componentProps: {
          disabled: schemaParams.futures === '现货',
          valueFormat: 'YYYY-MM-DD'
        },
        formItemProps: {}
      },
      table: {
        minWidth: 100,
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.real_arrival_date
          }
        }
      }
    },
    {
      field: 'inbound_batch',
      label: t('inventory.inbound_batch'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        minWidth: 160,
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.inbound_batch
          }
        }
      }
    },
    {
      field: 'last_audit_date',
      label: t('inventory.last_audit_date'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'initial_qty',
      label: t('inventory.initial_qty'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'available_qty',
      label: t('inventory.available_qty'),
      sortable: true, // 启用排序功能
      sortMethod: false, // 禁用前端排序，使用服务端排序
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'convertible_qty',
      label: t('inventory.convertible_qty'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'lock_qty',
      label: t('inventory.lock_qty'),
      sortable: true, // 启用排序功能
      sortMethod: false, // 禁用前端排序，使用服务端排序
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },

    {
      field: 'actual_available_qty',
      label: t('purchase.total_quantity_actual_available'),
      sortable: true, // 启用排序功能
      sortMethod: false, // 禁用前端排序，使用服务端排序
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },

    {
      field: 'currency',
      label: t('inventory.currency'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.currency
          }
        }
      },
      detail: {
        hidden: true
      }
    },
    {
      field: 'price',
      label: t('inventory.price'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.price
          }
        }
      },
      detail: {
        hidden: true
      }
    },
    {
      field: 'first_leg_logistics_fee',
      label: t('inventory.first_leg_logistics_fee'),
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.first_leg_logistics_fee
          }
        }
      },
      detail: {
        hidden: true
      }
    },
    {
      field: 'is_sale',
      label: t('inventory.is_sellable'),
      search: {
        component: 'Select',
        componentProps: {
          options: schemaParams.is_saleList ? schemaParams.is_saleList : []
        },
        value: ''
      },
      form: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => (
            <ElSwitch
              v-model={data.row.is_sale}
              inlinePrompt
              activeText="可售"
              inactiveText="不可售"
              activeValue={1}
              inactiveValue={0}
              onChange={() => schemaParams.handleChangeSale(data.row)}
            />
          )
        }
      },
      detail: {
        hidden: true
      }
    },
    {
      field: 'ccname_ids',
      label: '可售国家分类',
      form: {
        component: 'Select',
        componentProps: {
          multiple: true,
          collapseTags: true,
          maxCollapseTags: 2,
          placeholder: '请选择可售国家分类'
        },
        formItemProps: {
          rules: [required()],
          slots: {
            default: (formModel: any) => {
              const currentValue = formModel?.ccname_ids || []
              const hasGlobal = currentValue.includes(0)
              const originalOptions = schemaParams.ccList?.value || []

              return (
                <ElSelect
                  v-model={formModel.ccname_ids}
                  multiple
                  collapseTags
                  maxCollapseTags={5}
                  placeholder="请选择可售国家分类"
                  style="width: 100%"
                  onChange={(values: any[]) => {
                    // 如果选择了全球选项(value: 0)，则清除其他所有选项
                    if (values.includes(0)) {
                      formModel.ccname_ids = [0]
                    }
                    // 如果当前有全球选项，但新选择的值中没有全球选项，则允许正常选择
                    else if (currentValue.includes(0) && !values.includes(0)) {
                      formModel.ccname_ids = values.filter((v) => v !== 0)
                    }
                    // 其他情况正常处理
                    else {
                      formModel.ccname_ids = values
                    }
                  }}
                >
                  {originalOptions.map((option: any) => (
                    <ElOption
                      key={option.value}
                      label={option.label}
                      value={option.value}
                      disabled={hasGlobal && option.value !== 0}
                    />
                  ))}
                </ElSelect>
              )
            }
          }
        }
      },
      table: {
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.ccname_ids
              ?.map((item: any) => {
                return schemaParams.ccList.value.find((cc: any) => cc.value === item)?.label
              })
              .join(' ')
          }
        }
      }
    },
    {
      field: 'allow_zero_stock_sale',
      label: '是否允许零库存销售',
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        componentProps: {
          options: schemaParams.allowZeroOptions || []
        },
        formItemProps: {
          rules: [required()]
        }
      },
      table: {
        align: 'center',
        slots: {
          default: (data: any) => (
            <ElSwitch
              v-model={data.row.allow_zero_stock_sale}
              inlinePrompt
              activeText="允许"
              inactiveText="不允许"
              activeValue={1}
              inactiveValue={0}
              onChange={() => schemaParams.handleChangeAllowZeroStockSale(data.row)}
              // onChange={async () => {
              //   const newVal = data.row.allow_zero_stock_sale
              //   try {
              //     await setAllowZeroStockSaleApi({
              //       ids: [data.row.id],
              //       allow_zero_stock_sale: newVal
              //     })
              //     ElMessage.success('设置成功')
              //   } catch (e) {
              //     data.row.allow_zero_stock_sale = newVal === 1 ? 0 : 1
              //   }
              // }}
            />
          )
        }
      },
      detail: {
        hidden: true
      }
    },
    {
      field: 'creator',
      label: t('inventory.creator'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.creator_value
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.creator
          }
        }
      }
    },
    {
      field: 'create_time',
      label: t('inventory.create_time'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        headerAlign: 'center',
        align: 'center'
      }
    },
    {
      field: 'updater',
      label: t('inventory.updater'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.updater_value
          }
        }
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.updater
          }
        }
      }
    },
    {
      field: 'update_time',
      label: t('inventory.update_time'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return data.row.update_time
          }
        }
      }
    },
    {
      field: 'action',
      width: schemaParams.actionButtonsTemplate
        ? (schemaParams.actionButtonsTemplate?.length || 3) * 60 + 20 + 'px'
        : 'auto',
      label: t('tableDemo.action'),
      fixed: 'right',
      search: {
        hidden: true
      },
      form: {
        hidden: true
      },
      detail: {
        hidden: true
      },
      table: {
        headerAlign: 'center',
        align: 'center',
        slots: {
          default: (data: any) => {
            return schemaParams.actionButtonsTemplate
              ? schemaParams.actionButtonsTemplate?.template(data)
              : null
          }
        }
      }
    },
    //编辑仓库表单配置
    {
      field: 'arrival_batch',
      label: '批次',
      search: {
        hidden: true
      },
      form: {
        hidden: true
        // component: 'Input',
        // componentProps: {
        //   disabled: schemaParams.index === 2
        // }
      },
      table: {
        hidden: true
      },
      detail: {
        hidden: true
      }
    },
    {
      field: 'futures',
      label: '库存类型',
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        }
      },
      table: {
        hidden: true
      },
      detail: {
        slots: {
          default: (data: any) => {
            return data.futures
          }
        }
      }
    },
    {
      field: 'cost',
      label: t('inventory.conversion.costPrice'),
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          disabled: schemaParams.index === 2
        },
        formItemProps: {}
      },
      table: {
        hidden: true
      }
    },
    {
      field: 'is_sale',
      label: '是否可售',
      search: {
        hidden: true
      },
      form: {
        component: 'Select',
        componentProps: {
          options: schemaParams.saleOptions || []
        },
        formItemProps: {
          rules: [required()]
        }
      },
      table: {
        hidden: true
      },
      detail: {
        hidden: true
      }
    },
    // 备注
    {
      field: 'notes',
      label: '备注',
      search: {
        hidden: true
      },
      form: {
        component: 'Input',
        componentProps: {
          type: 'textarea',
          maxlength: 80
        },
        formItemProps: {}
      },
      table: {
        minWidth: 200,
        headerAlign: 'center'
        // hidden: true
      }
    },
    {
      field: 'if_tlz',
      label: '是否提篮子库存',
      search: {
        component: 'Select',
        componentProps: {
          options: [
            { label: '否', value: 0 },
            { label: '是', value: 1 }
          ]
        },
        value: ''
      },
      form: {
        hidden: true
      },
      table: {
        hidden: true
      },
      detail: {
        hidden: true
      }
    },
    {
      field: 'allow_zero_stock_sale',
      label: '是否允许零库存销售',
      search: {
        component: 'Select',
        componentProps: {
          options: [
            { label: '不允许', value: 0 },
            { label: '允许', value: 1 }
          ]
        },
        value: ''
      },
      form: {
        hidden: true
      },
      table: {
        hidden: true
      },
      detail: {
        hidden: true
      }
    },
    {
      search: {
        hidden: true
      },
      form: {
        formItemProps: {
          slots: {
            default: () => <ElDivider></ElDivider>
          }
        },
        colProps: {
          span: 24
        }
      },
      table: {
        hidden: true
      },
      detail: {
        hidden: true
      }
    }
  ])

  return {
    crudSchemas
  }
}
